<template>
  <v-flex
    xs12
    sm8
  >
    <v-card>
      <v-list subheader>
        <v-subheader>Todo List</v-subheader>
        <v-text-field
          name="add"
          label="Todo"
          placeholder="Press ENTER to add a new line."
          v-model="input"
          @keyup.enter="add"
        />
        <v-list-tile
          v-for="(l,i) in list"
          :key="i"
        >
          <v-list-tile-action>
            <v-checkbox v-model="l.done" />
          </v-list-tile-action>
          <v-list-tile-content>
            <v-text-field
              v-model="l.name"
              :readonly="l.ro"
              :clearable="!l.ro"
              auto-grow
              @dblclick="update(i)"
              @blur="save(i)"
              @keyup.enter="save(i)"
              @keyup.esc="undo(i)"
            />
          </v-list-tile-content>
          <v-list-tile-action>
            <v-btn
              small
              @click="remove(i)"
            >
              REMOVE
            </v-btn>
          </v-list-tile-action>
        </v-list-tile>
      </v-list>
    </v-card>
  </v-flex>
</template>

<script>
export default {
  data: () => ({
    list: [
      { name: '理发', done: true, ro: true },
      { name: '学习vue', done: true, ro: true },
      { name: '学习php', done: false, ro: true },
      { name: '学习node', done: false, ro: true },
    ],
    index: -1,
    input: '',
    before: '',
  }),
  methods: {
    add() {
      if (this.input == '') return;
      const item = {
        name: this.input,
        done: false,
        ro: true,
      };
      this.list.push(item);
      this.input = '';
    },
    remove(i) {
      this.list.splice(i, 1);
    },
    update(i) {
      this.index = i;
      this.before = this.list[i].name;
      this.list[i].ro = false;
    },
    save(i) {
      this.list[i].ro = true;
      this.index = -1;
    },
    undo(i) {
      this.list[i].ro = true;
      this.list[i].name = this.before;
      this.before = '';
      this.index = -1;
    },
  },
  computed: {},
};
</script>
